import CryptoJS from 'crypto-js';

const ASE_KEYS = process.env.VUE_APP_ASE_KEYS
const SECRET_KEY = CryptoJS.enc.Utf8.parse(ASE_KEYS);

/**
 * AES加密
 * @param data 需要加密的字符串
 * @returns {string}
 */
export function encrypt(data) {
    const encrypted = CryptoJS.AES.encrypt(
        CryptoJS.enc.Utf8.parse(data),
        SECRET_KEY,
        {
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7
        }
    );
    return encrypted.ciphertext.toString();
}

/**
 * AES解密
 * @param encryptedData 需要解密的字符串
 * @returns {string}
 */
export function decrypt(encryptedData) {
    const decrypted = CryptoJS.AES.decrypt(
        encryptedData,
        SECRET_KEY,
        {
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7
        }
    );
    return decrypted.toString(CryptoJS.enc.Utf8);
}

export function downloadExcel(res, name) {
    const fileName = `${name}-${[new Date().getFullYear(), (new Date().getMonth() + 1).toString().padStart(2, '0'), new Date().getDate().toString().padStart(2, '0')].join('-')}-${[new Date().getHours(), new Date().getMinutes(), new Date().getSeconds()].map(v => v.toString().padStart(2, '0')).join('-')}.xlsx`;
    const blob = new Blob([res.data], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = fileName;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
}
